package edu.school.interceptor;

import edu.school.entity.Admin;
import edu.school.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author kabuda
 * @create 2023-10-01 10:24
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestURI = httpServletRequest.getRequestURI();
        //放行登录注册
        if(requestURI.indexOf("/login")>=0||requestURI.indexOf("/toRegister")>=0||requestURI.indexOf("/register")>=0||requestURI.indexOf("/utils/upload")>=0){
            return true;
        }
        //如果已经登录放行
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        Admin admin = (Admin) httpServletRequest.getSession().getAttribute("admin");
        if(user!=null||admin!=null){
            return true;
        }
        httpServletRequest.setAttribute("msg","请登录！");
        httpServletRequest.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(httpServletRequest,httpServletResponse);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
